package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.*;
import com.atguigu.result.Result;
import com.atguigu.service.*;
import com.atguigu.vo.HouseQueryVo;
import com.atguigu.vo.HouseVo;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨林
 * @create 2022-09-23 20:12 星期五
 * description:
 */
@RestController
@RequestMapping("/house")
public class HouseController {

    @Reference
    private HouseService houseService;

    @Reference
    private CommunityService communityService;

    @Reference
    private HouseBrokerService  houseBrokerService;

    @Reference
    private HouseImageService houseImageService;

    @Reference
    private UserFollowService userFollowService;

    @RequestMapping("/list/{pageNum}/{pageSize}")
    public Result< PageInfo<HouseVo>> list(@PathVariable Integer pageNum,
                       @PathVariable Integer pageSize, @RequestBody HouseQueryVo houseQueryVo){

        PageInfo<HouseVo> page = this.houseService.finListPage(pageNum,pageSize,houseQueryVo);

        //返回数据
        return Result.ok(page);
    }



    @GetMapping("info/{id}")
    public Result info(@PathVariable Long id, HttpServletRequest request){

        //通过Map集合来保存数据
        Map map = new HashMap<>();
        House house = houseService.getById(id);
        Community community = communityService.getById(house.getCommunityId());
        List<HouseBroker> houseBrokerList = houseBrokerService.findListByHouseId(id);
        List<HouseImage> houseImage1List = houseImageService.findList(id, 1);

        //将前端所需的数据放入map集合中
        map.put("house",house);
        map.put("community",community);
        map.put("houseBrokerList",houseBrokerList);
        map.put("houseImage1List",houseImage1List);

        //从session中获取用户信息
        UserInfo userInfo = (UserInfo)request.getSession().getAttribute("USER");
        boolean isFollow = false;
        //已经登录 并且当前用户已经关注了该房屋
        if (userInfo != null){
            Long userId = userInfo.getId();
            //通过访问数据库 查看当前用户是否已经关注房源
            isFollow = userFollowService.isFollow(id,userId);

        }
        map.put("isFollow",isFollow);

        return Result.ok(map);
    }

}
